<?php

namespace app\modules\user\services;

use app\common\services\BaseService;
use app\config\Constants;
use app\models\User;
use app\models\UserInfoStore;
use app\models\UserInfoUser;
use app\modules\user\forms\info\StoreForm;
use app\modules\user\forms\info\UserForm;

class InfoService extends BaseService{

    /**
     * 获取信息
     * @return array|null
     * @throws \yii\base\InvalidConfigException
     */
    public static function getInfoById(){
        /**
         * @var User $user
         */
        $user = \Yii::$app->getModule("user")->get("user")->getIdentity();
        return [
            'store'=>UserInfoStore::findOne($user->getId()),
            'user'=>UserInfoUser::findOne($user->getId()),
        ];
    }

    /**
     * 店铺
     * @param StoreForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function store(StoreForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = UserInfoStore::findOne($form->user_id);
        if(!$model){
            $model = new UserInfoStore();
        }
        if($model->is_verify == Constants::VERIFY_SUCCESS){
            self::setError(\Yii::t("app","审核已通过,无需重新提交"));
            return false;
        }
        $model->setAttribute("is_verify",Constants::VERIFY_WAIT);
        $model->setAttribute("verify_msg","");
        $model->setAttributes($form->getAttributes(),false);

        return ($model->getIsNewRecord() ? $model->insert() : $model->update()) !== false;
    }

    /**
     * 用户
     * @param UserForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function user(UserForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = UserInfoUser::findOne($form->user_id);
        if(!$model){
            $model = new UserInfoUser();
        }
        if($model->is_verify == Constants::VERIFY_SUCCESS){
            self::setError(\Yii::t("app","审核已通过,无需重新提交"));
            return false;
        }
        $model->setAttribute("is_verify",Constants::VERIFY_WAIT);
        $model->setAttribute("verify_msg","");
        $model->setAttributes($form->getAttributes(),false);
        return ($model->getIsNewRecord() ? $model->insert() : $model->update()) !== false;
    }
}